﻿using System;
using UnityEngine;
using UnityEngine.Networking;

public class HttpComponent:MonoBehaviour
{
    UnityWebRequest request;
    TaskCompletionSource<UnityWebRequest> taskCompletionSource;
    
    public void Get(string url, TaskCompletionSource<UnityWebRequest> taskCompletionSource)
    {
        this.taskCompletionSource = taskCompletionSource;
        url = url.Replace(" ", "%20");
        request = UnityWebRequest.Get(url);
        
    }

    public void Post(string url, WWWForm formData, TaskCompletionSource<UnityWebRequest> taskCompletionSource)
    {
        this.taskCompletionSource = taskCompletionSource;
        url = url.Replace(" ", "%20");
        request = UnityWebRequest.Post(url, formData);
    }

    public void StartRequest()
    {
        gameObject.name = request.url;
        request.SendWebRequest();
        gameObject.SetActive(true);
    }

    public void SetCancel()
    {
        taskCompletionSource.SetCancel();
    }

    public CompletionState GetState()
    {
        return taskCompletionSource.GetState();
    }

    public void Update()
    {
        if (request == null)
            return;

        if(taskCompletionSource.GetState() != CompletionState.Pending)
        {
            request = null;
            gameObject.SetActive(false);
            return;
        }

        if (!request.isDone)
            return;

        if(!string.IsNullOrEmpty(request.error))
        {
            taskCompletionSource.SetException(new Exception(request.error));
            return;
        }
        
        taskCompletionSource.SetResult(request);
    }
}
